package com.baomidou.springwind.controller;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.framework.common.util.DateUtil;
import com.baomidou.framework.controller.SuperController;
import com.baomidou.framework.upload.UploadFile;
import com.baomidou.framework.upload.UploadMsg;
import com.baomidou.framework.upload.UploadMultipartRequest;
import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.annotation.Permission;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.springwind.common.HoorayosHelper;
import com.baomidou.springwind.entity.Member;
import com.baomidou.springwind.entity.MemberApp;
import com.baomidou.springwind.entity.Setting;
import com.baomidou.springwind.entity.Wallpaper;
import com.baomidou.springwind.service.IMemberAppService;
import com.baomidou.springwind.service.IMemberService;
import com.baomidou.springwind.service.ISettingService;
import com.sun.tools.internal.ws.wsdl.framework.Entity;

/**
 * <p>
 *  对话框控制器
 * </p>
 *
 * @author Koumiba
 * @since 2017-03-24
 */
@Controller
@RequestMapping("/sysapp/dialog")
public class DialogController extends SuperController {
	@Autowired
	private IMemberAppService memberAppService;
	/**
	 * 主页
	 */
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/app")
	public String app(Model model) {
		model.addAttribute("errorCode", HoorayosHelper.getErrorCodeMap());
		//验证是否登入
		if(!HoorayosHelper.checkLogin(request)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noLogin"));
			return "error";
		}
		String id = request.getParameter("id");
		if(id != null && !id.equals("")){
			MemberApp app = memberAppService.selectById(Integer.parseInt(id));
			
			model.addAttribute("app", app);
			model.addAttribute("id", id);
		}
	
		return "/sysapp/dialog/app";
	}
	
	/**
	 * 我的应用编辑页
	 */
	@ResponseBody
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/appajax")
	public String ajax(Model model) {
		String ac = request.getParameter("ac");
		if(ac.equals("edit")){
			String tbid = request.getParameter("id");
			int mid = HoorayosHelper.getMemberId(request);
			EntityWrapper ew = new EntityWrapper<MemberApp>();
			ew.where("tbid="+tbid+" AND member_id="+mid);
			MemberApp mapp = new MemberApp().selectOne(ew);
			mapp.setIcon(request.getParameter("val_icon"));
			mapp.setName(request.getParameter("val_name"));
			mapp.setWidth(Integer.parseInt(request.getParameter("val_width")));
			mapp.setHeight(Integer.parseInt(request.getParameter("val_height")));
			mapp.setIsresize(Integer.parseInt(request.getParameter("val_isresize")));
			mapp.setIsopenmax(Integer.parseInt(request.getParameter("val_isopenmax")));
			mapp.setIsflash(Integer.parseInt(request.getParameter("val_isflash")));
			memberAppService.insertOrUpdate(mapp);
			
			Map<String, String> result = new HashMap<String, String>();
			result.put("info", "");
			result.put("status", "y");
			return JSONUtils.toJSONString(result);				
		}else if(ac.equals("uploadImg")){
			UploadMsg msg = new UploadMsg();
			try {
				UploadMultipartRequest umr = new UploadMultipartRequest(request, getSaveDir(), 2048000);
				umr.upload();
				Enumeration<?> files = umr.getFileNames();
				while ( files.hasMoreElements() ) {
					String name = (String) files.nextElement();
					UploadFile cf = umr.getUploadFile(name);
					if ( cf != null ) {
						Map<String, String> info = new HashMap<String, String>();
						info.put("url", getSurlPath()+cf.getFilename());
						info.put("fileType", cf.getType());
						info.put("original", cf.getOriginalFileName());
						info.put("state", cf.getUploadCode().key()+"");
						return JSONUtils.toJSONString(info);
					}
				}
			}catch ( IOException e ) {
				logger.error("uploadFile error. ", e);
			}	
		}
		return "";
	}
	
	/*************************
	 *    私有方法 
	 *************************/
	
	/**
	 * <p>
	 * 上传文件存放目录 uploads/member/{memberId}/shortcut{yyyy}{mm}{dd}/{time}{rand:6}
	 * </p>
	 */
	private String getSaveDir() {
		StringBuffer filePath = new StringBuffer(session.getServletContext().getRealPath("/"));
		filePath.append(File.separator).append("WEB-INF").append(File.separator).append("static")
		.append(File.separator).append("uploads").append(File.separator).append("member").append(File.separator).append(HoorayosHelper.getMemberId(request))
		.append(File.separator).append("shortcut").append(File.separator);
		filePath.append(DateUtil.format(new Date(), "yyyyMMdd"));
		File file = new File(filePath.toString());
		if ( !file.exists() ) {
			file.mkdirs();
		}
		
		return file.getPath();
	}
	/**
	 * 获取图片的web访问路径
	 * @return String
	 * koumiba
	 * 2017年4月8日
	 */
	private String getSurlPath(){
		return "/static/uploads/member/"+HoorayosHelper.getMemberId(request)+"/shortcut/"+DateUtil.format(new Date(), "yyyyMMdd")+"/";
	}
}
